var currentUserId = "";
var currentUserName = "";
var currentCourseId = "";
var currentCourseName = "";
var currentAssignmentId = "";
var currentAssignmentName = "";
var currentActivityId = "";
var currentActivityName = "";
$(function(){
	$.ajax({
		url:'/pad/getSessionUser',
		success:function(user){
			currentUserId = user.id;
			currentUserName = user.realname;
			$("#user").html(user.realname+' <span class="caret"></span>');
		}
	});
	templateListView();
});
/**
 * 提交表单
 */
function submitForm(formSelecter,modalSelecter){
	// 异步提交表单
    $(formSelecter).ajaxSubmit({  
        type:'post',
        resetForm: true,
        success:function(data){ 
        	if(data=='success'){
        		$('#data-table').bootstrapTable('refresh');
        		$(modalSelecter).modal('hide');
        	}else{
        		alert(data);
        	}
        },
        error:function(msg){
        	alert(msg.statusText);
        }
    });  
}
function manageConst(courseId,courseName,assignmentId,assignmentName){
	currentCourseId = courseId?courseId:"";
	currentCourseName = courseName?courseName:"";
}
function templateListView(){
	$('#breadcrumb').html('<li class="active">评论模板列表</li>');
	$('#toolbar').html('<button class="btn btn-info" data-toggle="modal" data-target="#createTemplateModal"><span class="glyphicon glyphicon-plus"></span>创建模板</button>');
	$('#data-table').bootstrapTable('destroy');
	$('#data-table').bootstrapTable({
	    url: '/pad/comment/getTemplates',
	    pagination:true,
	    search:true,
	    undefinedText:'',
	    striped:true,
	    showRefresh:true,
	    toolbar:'#toolbar',
	    idField:'id',
	    columns: [
	    	{field: 'templateName',title: '模板名称'},
	    	{field: 'templateType',title: '模板类型'},
	    	{field: 'op',title: '操作',width:100,formatter:function(value,row,index){
	    		return '<a href="javascript:questionListView(\''+row.id+'\',\''+row.templateName+'\',\''+row.templateType+'\');" class="btn btn-info btn-xs">进入</a> <a href="javascript:deleteTemplate(\''+row.id+'\');" class="btn btn-danger btn-xs">删除</a>';
	    	}}]
	});
}
function deleteTemplate(templateId){
	$.ajax({
		url:'/pad/comment/deleteTemplate?templateId='+templateId,
		success:function(msg){
			if(msg=="success"){
				$('#data-table').bootstrapTable('refresh');
			}
		}
	});
}
function questionListView(templateId,templateName,templateType){
	$('input[name="templateId"]').val(templateId);
	$('#breadcrumb').html('<li><a href="javascript:templateListView();">评论模板列表</a></li><li class="active">'+templateName+'('+templateType+')'+'</li>');
	if(templateType=="反馈评论模板"){
		$('#toolbar').html('<button class="btn btn-info" data-toggle="modal" data-target="#createQuestionModal"><span class="glyphicon glyphicon-plus"></span>创建反馈问题</button>');
		$('#data-table').bootstrapTable('destroy');
		$('#data-table').bootstrapTable({
		    url: '/pad/comment/getReplyTemplateQuestions?templateId='+templateId,
		    pagination:true,
		    search:true,
		    undefinedText:'',
		    striped:true,
		    showRefresh:true,
		    toolbar:'#toolbar',
		    // detailView:true,
		    idField:'id',
		    columns: [
		    	{field: 'title',title: '编号'},
		    	{field: 'question',title: '评论问题'}, 
		    	{field: 'score',title: '分数'},
		    	{field: 'op',title: '操作',width:100,formatter:function(value,row,index){
		    		return '<a href="javascript:deleteQuestion(\''+row.id+'\');" class="btn btn-danger btn-xs">删除</a>';
		    	}}]
		});
	}
	else if(templateType=="互评评论模板"){
		$('#toolbar').html('<button class="btn btn-info" data-toggle="modal" data-target="#createMutualQuestionModal"><span class="glyphicon glyphicon-plus"></span>创建互评问题</button>');
		$('#data-table').bootstrapTable('destroy');
		$('#data-table').bootstrapTable({
		    url: '/pad/comment/getTemplateQuestions?templateId='+templateId,
		    pagination:true,
		    search:true,
		    undefinedText:'',
		    striped:true,
		    showRefresh:true,
		    toolbar:'#toolbar',
		    // detailView:true,
		    idField:'id',
		    columns: [
		    	{field: 'question',title: '评论问题'},
		    	{field: 'score',title: '分数'}, 
		    	{field: 'op',title: '操作',width:100,formatter:function(value,row,index){
		    		return '<a href="javascript:deleteQuestion(\''+row.id+'\');" class="btn btn-danger btn-xs">删除</a>';
		    	}}]
		});
	}
	
}
function deleteQuestion(questionId){
	$.ajax({
		url:'/pad/comment/deleteTemplateQuestion?questionId='+questionId,
		success:function(msg){
			if(msg=="success"){
				$('#data-table').bootstrapTable('refresh');
			}
		}
	});
}
function activityListView(assignmentId,assignmentName,startDate,endDate){
	manageConst(currentCourseId,currentCourseName,assignmentId,assignmentName);
	$('input[name="assignmentId"]').val(assignmentId);
	console.log(startDate + " " +new Date(parseInt(startDate)).format('yyyy-MM-dd'));
	$('#createActivityModal').find('.date-start').datetimepicker('setStartDate',new Date(parseInt(startDate)).format('yyyy-MM-dd'));
	$('#createActivityModal').find('.date-end').datetimepicker('setEndDate',new Date(parseInt(endDate)).format('yyyy-MM-dd'));
	$('#breadcrumb').html('<li><a href="/pad">首页</a></li><li><a href="javascript:courseListView();">课程列表</a></li><li><a href="javascript:assignmentListView(\''+currentCourseId+'\',\''+currentCourseName+'\');">'+currentCourseName+'</a></li><li class="active">'+assignmentName+'</li>');
	$('#toolbar').html('<button class="btn btn-info" data-toggle="modal" data-target="#createActivityModal"><span class="glyphicon glyphicon-plus"></span>创建活动</button>');
	$('#data-table').bootstrapTable('destroy');
	$('#data-table').bootstrapTable({
	    url: 'activity/getActivities?assignmentId='+assignmentId,
	    pagination:true,
	    search:true,
	    undefinedText:'',
	    striped:true,
	    showRefresh:true,
	    detailFormatter:function(index,row){
	    	var html = '';
	    	$.ajax({
	    		async: false,
	    		url:'activity/getActivityGroupVisions?activityId='+row.id,
	    		success:function(activityGroupVisionList){
	    			html += '<table>';
	    			$.each(activityGroupVisionList, function(index, activityGroupVision){
    	                html += '<tr>';
    	                html += '<td>'+activityGroupVision.groupName+'</td>'
    	                html += '<td><form action="activity/saveActivityGroupVision"><input type="hidden" name="id" value="'+activityGroupVision.id+'"/><input type="hidden" name="activityId" value="'+activityGroupVision.activityId+'"/><input type="hidden" name="groupId" value="'+activityGroupVision.groupId+'"/><input type="hidden" name="groupName" value="'+activityGroupVision.groupName+'"/><select name="visionType"><option value="">请选择</option>';
    	                $.ajax({
    	    	    		async: false,
    	    	    		cache: true,
    	    	    		url:'getDictionary?code=VISION',
    	    	    		success:function(dictionaryList){
    	    	    			$.each(dictionaryList, function(index, dictionary){
    	    	    				if(dictionary.dictCode==activityGroupVision.visionType)
    	    	    					html += '<option value='+dictionary.dictCode+' selected="selected">'+dictionary.dictTitle+'</option>';
    	    	    				else
    	    	    					html += '<option value='+dictionary.dictCode+'>'+dictionary.dictTitle+'</option>';
    	    	    			});
    	    	    		}
    	                });
    	                html += '</select>';
    	                html += '<input type="submit" value="保存"/>';
    	                html += '</form></td></tr>';
	    			});
	    			html += '</table>';
	    		}
	    	});
	    	return html;
	    },
	    toolbar:'#toolbar',
	    detailView:true,
	    idField:'id',
	    onEditableSave: function (field, row, oldValue, $el) {
	    	var dataStr = JSON.stringify(row).replace(/:/g,'=').replace(/{/g,'').replace(/}/g,'').replace(/,/g,'&').replace(/"/g,'').replace(/null/g,'');
            $.ajax({
                url: "activity/createActivity?"+dataStr,
                success: function (data, status) {
                    if (status == "success") {
                    }else{
                    	alert(data);
                    }
                },
                error: function () {
                    alert("Error");
                },
                complete: function () {

                }

            });
        },
	    columns: [{field: 'checkbox',checkbox:true},
	    	{field: 'assignmentType',title: '活动状态',width:100},
	    	{field: 'op',title: '操作',width:100,formatter:function(value,row,index){
	    		return '<a href="javascript:getAssignmentList(\''+row.id+'\',\''+row.courseName+'\');" class="btn btn-info btn-xs">选择</a>';
	    	}}, 
	    	{field: 'activityName',title: '活动名称',editable:true},
	    	{field: 'description',title: '活动描述',editable:true},
	    	{field: 'startDate',title: '开始时间',editable:true,width:100},
	    	{field: 'endDate',title: '结束时间',editable:true,width:100}]
	});
}

$(function(){
    /**
	 * 时间对象的格式化;
	 */  
    Date.prototype.format = function(format) {  
        /*
		 * eg:format="yyyy-MM-dd hh:mm:ss";
		 */  
        var o = {  
            "M+" : this.getMonth() + 1, // month
            "d+" : this.getDate(), // day
            "h+" : this.getHours(), // hour
            "m+" : this.getMinutes(), // minute
            "s+" : this.getSeconds(), // second
            "q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
            "S" : this.getMilliseconds()  
            // millisecond
        }  
      
        if (/(y+)/.test(format)) {  
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
        }  
        for (var k in o) {  
            if (new RegExp("(" + k + ")").test(format)) {  
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));  
            }  
        }  
        return format;  
    }  
});